package letsjava.outer;

import java.io.IOException;

import javax.script.*;

import letsjava.utils.*;

public class NSJavascript {
	ScriptEngineManager manager;
	ScriptEngine se;
	Invocable invocableEngine;
	
	public NSJavascript(){
		manager = new ScriptEngineManager();
		se = manager.getEngineByName("javascript");
		invocableEngine = (Invocable) se;
	}
	
	public void evalFile(String filename) throws ScriptException, IOException{
		se.eval(NSFile.fileGetContents2(filename));
	}
	
	public void evalString(String filename) throws ScriptException, IOException{
		se.eval(filename);
	}
	
	public String callFunction(String funcName,String param1) throws ScriptException, NoSuchMethodException{
		return (String) invocableEngine.invokeFunction(
				funcName, param1);
	}
	
	public String callFunction(String funcName,String param1,String param2) throws ScriptException, NoSuchMethodException{
		return (String) invocableEngine.invokeFunction(
				funcName, param1,param2);
	}
	
	public String callFunction(String funcName,String param1,String param2,String param3) throws ScriptException, NoSuchMethodException{
		return (String) invocableEngine.invokeFunction(
				funcName, param1,param2,param3);
	}
	
	public static void main(String[] args) throws Exception {

		
		NSJavascript a = new NSJavascript();
		a.evalFile(System.getProperty("user.dir")+"/data/outer.js");
		System.out.println(a.callFunction("add", "133","2"));
		
		
		/*ScriptEngineManager manager = new ScriptEngineManager();

		for (ScriptEngineFactory f : manager.getEngineFactories()) {
			System.out.println(f);
		}

		ScriptEngine se = manager.getEngineByName("javascript");
		try {
			// 调用直接JAVASCRIPT语句
			se.eval("println('111');");
			String tmpstr = "test string";
			se.eval(("println('" + tmpstr + "');"));

			// 调用无参数方法JAVASCRIPT函数
			se.eval("function sayHello() {"
			        + "  print('Hello '+strname+'!');return 'my name is '+strname;"
			        + "}");
			Invocable invocableEngine = (Invocable) se;
			//se.put("strname", "test6name");
			String callbackvalue = (String) invocableEngine
			        .invokeFunction("sayHello");
			System.out.println(callbackvalue);

			// 调用有参数JAVASCRIPT函数
			se.eval("function sayHello2(strname2) {"
			        + "  print('Hello '+strname+'!');return 'my name is '+strname2;"
			        + "}");
			callbackvalue = (String) invocableEngine.invokeFunction(
			        "sayHello2", "testname2");
			System.out.println(callbackvalue);

		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

	}
}
